package com.sky.jtail.conf;

import com.sky.jtail.domain.AppConstant;
import com.sky.jtail.domain.AppContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Service
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Autowired
    private AppContainer appContainer;

    /**
     * 握手之前，若返回false，则不建立链接 *
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse
            response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        //获取参数
        String wsAuth = servletRequest.getParameter(AppConstant.wsAuth);
        attributes.put(AppConstant.wsAuth, wsAuth);
        String fileKey = servletRequest.getParameter(AppConstant.fileKey);
        attributes.put(AppConstant.fileKey, fileKey);
        //可以在此处进行权限验证，当用户权限验证通过后，进行握手成功操作，验证失败返回false

        if(!appContainer.authValues.containsKey(wsAuth)){
            log.error("认证失败...");
            return false;
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse
            response, WebSocketHandler wsHandler, Exception exception) {
        log.error("WebSocket Handshake success");
    }
}